package com.mayikt.spike.consumer;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.spike.mapper.OrderMapper;
import com.mayikt.spike.mapper.SeckillMapper;
import com.mayikt.spike.mapper.entity.Order;
import com.mayikt.spike.mapper.entity.Seckill;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Slf4j
public class StockConsumer {
    @Autowired
    private SeckillMapper seckillMapper;
    @Autowired
    private OrderMapper orderMapper;

    @RabbitListener(queues = "modify_inventory_queue")
    @Transactional
    public void process(Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        String messageId = message.getMessageProperties().getMessageId();
        String msg = new String(message.getBody(), "UTF-8");
        log.info(">>>messageId:{},msg:{}", messageId, msg);
        JSONObject jsonObject = JSONObject.parseObject(msg);
        // 1.获取秒杀id
        Long seckillId = jsonObject.getLong("seckillId");
        Seckill seckillEntity = seckillMapper.findBySeckillId(seckillId);
        if (seckillEntity == null) {
            log.warn("seckillId:{},商品信息不存在!", seckillId);
            return;
        }
        Long version = seckillEntity.getVersion();
        int seckillRow = seckillMapper.inventoryDeduction(seckillId, version);
        if (seckillRow == 0) {
            log.info(">>>seckillId:{}修改库存失败>>>>inventoryDeduction返回为{} 秒杀失败！", seckillId, seckillRow);
            return;
        }
        // 2.添加秒杀订单
        Order order = new Order();
        String phone = jsonObject.getString("phone");
        order.setUserPhone(phone);
        order.setSeckillId(seckillId);
        order.setState(1);
        order.setCreateTime(LocalDateTime.now());
        int orderRow = orderMapper.insert(order);
        if ( orderRow == 0) {
            return;
        }
        log.info(">>>修改库存成功seckillId:{}>>>>inventoryDeduction返回为{} 秒杀成功", seckillId, orderRow);
    }
}
